package com.kt.mes.util;


import com.kt.mes.mqtt.PushCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttUtil {

    static String broker = "tcp://39.106.111.79:1883";
    static String clientId = "emqx_mes";

    private static MqttClient client;

    static {
        MemoryPersistence persistence = new MemoryPersistence();
        try {

            client = new MqttClient(broker, clientId, persistence);

            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName("emqx_mes");
            connOpts.setPassword("emqx_mes_password".toCharArray());
            // 保留会话
            connOpts.setCleanSession(true);
            client.setCallback(new PushCallback());
            // 建立连接
            System.out.println("Connecting to broker: " + broker);
            client.connect(connOpts);

            System.out.println("MQTT broker 已连接");

        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }

    }

    public static MqttClient getClient(){

        return client;
    }



    public static void pushData(String topic,int qos,String data){
        MqttClient client=getClient();
        //System.out.println(data);
        MqttMessage message = new MqttMessage(data.getBytes());
        message.setQos(qos);
//        QoS0，At most once，至多一次；
//        QoS1，At least once，至少一次；
//        QoS2，Exactly once，确保只有一次。
        try {
            client.publish(topic, message);
           // System.out.println("Message published");
        } catch (MqttException e) {
            e.printStackTrace();
        }


    }

    public static  void subTopic(String subTopic,int qos){

        MqttClient client=getClient();
        try {
            client.subscribe(subTopic);
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }
}
